package com.multisource.myself.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * @author chencb 解决多个数据源的冲突问题
 */
@Configuration
@EnableConfigurationProperties(PrestoProperties.class)
public class GlobalDataSourceConfig {

    @Autowired
    private PrestoProperties prestoProperties;

    @Bean(name = "prestoDataSource", initMethod = "init")
    public DataSource prestoDataSource() {
        DruidDataSource prestdDataSource = new DruidDataSource();
        prestdDataSource.setUrl(prestoProperties.getUrl());
        prestdDataSource.setTestWhileIdle(false);
        prestdDataSource.setUsername(prestoProperties.getUsername());
        prestdDataSource.setDriverClassName(prestoProperties.getDriverClassName());
        return prestdDataSource;
    }

    @Bean(name = "prestoTemplate")
    public JdbcTemplate prestoJdbcTemplate(@Qualifier("prestoDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}